<template>
  <div class="tree-canvas">
    <div class="hierarchy-tree">
      <el-scrollbar>
        <div id="small-menu" class="menu" v-show="menuFlag"
             :style="{'top':myMenuTop+'px','left':myMenuLeft+'px'}">
          <div>
            <span>{{menuData["CompanyName"]}}</span><br/>
            <span> {{menuData["CRMID"]}}</span><br/>
            <span>{{menuData["state"]}}</span><br/>
            <!-- @click="turnDetails" -->
            <el-button type="primary" :disabled="menuData['CompanyName']==''" class="menu-btn"><i class="el-icon-arrow-right"></i></el-button>
          </div>
        </div>
        <div class="tree-chart-main">
          <div id="tree-chart" >
          </div>
        </div>

      </el-scrollbar>
      <div class="hierarchy-state">
        <div v-if="state1" class="state state3" @click="highlight(1)">Traded in the past year <span></span></div>
        <div v-if="state2" class="state state2" @click="highlight(2)">Traded in the past three years <span></span></div>
        <div v-if="state3" class="state state1" @click="highlight(3)">Didn't trade in the past three years <span></span></div>
        <div v-if="state4" class="state state4" @click="highlight(4)">Didn't trade for more than three years <span></span></div>
      </div>
    </div>
  </div>
</template>
 
<script>
// let echarts = require('echarts/lib/echarts');
let echarts = require('echarts');
export default {
  props: {
    treeCanvas: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data () {
    return {
      myChart: {},
      key: 1,
      searchValue: '1213612452',
      searchName: '',
      state1: false,
      state2: false,
      state3: false,
      state4: false,
      dialogVisible: false,
      bReady: false,
      cTooltip: "",
      sLastDateInputofDoAjaxGetTooltip: "",
      chartDataFlag: false,
      menuFlag: false,
      menuData: {
        "CompanyName": '',
        "bp_id": '',
        "ContactAddress": '',
        "state": ''
      },
      myMenuTop: 0,
      myMenuLeft: 0,
      searchId: null,
      parentNode: null,
      node: null,
      nodeFlag: null,
      visitData: {
        "customer": "",
        "customer_name": "",
        "type": ""
      }
    }
  },
  mounted() {
    console.log(this.treeCanvas)
    let res = [this.treeCanvas]
    this.getNode(res[0].children, this.searchValue)
    this.dataFun(res[0])
    this.chartInit(res)
  },
  methods: {
    highlightData(obj) {
      let that = this;
      obj["label"] = this.highlightColor(obj)
      if (obj.children) {
        obj.children.forEach(function (key) {
          that.highlightData(key)
        })
      } else {
        return obj
      }
    },
    highlight(key) {
      this.key = key
      this.highlightData(this.chartData[0])
      this.chartInit(this.chartData)
    },
    chartInit(data) {
      let that = this
      this.myChart = echarts.init(document.getElementById('tree-chart'));
      this.myChart.setOption({
        tooltip: {
          show: true,
          backgroundColor: '#FFF4E5',//背景颜色（此时为默认色）
          borderColor: '#E4C3A5',
          borderWidth: 1,
          textStyle: {
            color: '#7E7E7E'
          },
          formatter: function (d) {
            return d.data['CompanyName']
          }
        },
        series: [
          {
            type: 'tree',
            data: data,
            top: 125,
            left: "10%",
            bottom: 300,
            right: "30%",
            symbolSize: [210, 29],
            symbol: "rect",
            borderColor: '#fff',
            initialTreeDepth: 1,
            lineStyle: {
              color: "#82B4E8",
              curveness: 0.5
            },
            label: {
              normal: {
                position: [-4, 15],
                verticalAlign: 'middle',
                align: 'left',
                backgroundColor: '#DAEAFF',
                color: '#585858',
                borderRadius: 4,
                overflow: 'hidden',
                padding: 3,
                formatter: [
                  '{box|{b}}'
                ].join('\n'),
                rich: {
                  box: {
                    height: 25,
                    width: 220,
                    fontSize: 12,
                    color: '#585858',
                    padding: [0, 6],
                    rotate: -90,
                    align: 'left',
                  }
                },
              }
            },
            leaves: {
              label: {
                position: [-4, 15],
                normal: {
                  verticalAlign: 'middle',
                  backgroundColor: '#DAEAFF',
                  borderRadius: 4,
                  overflow: 'hidden',
                  align: 'left',
                  formatter: [
                    '{box|{b}}'
                  ].join('\n'),
                  rich: {
                    box: {
                      height: 25,
                      width: 220,
                      fontSize: 12,
                      color: '#585858',
                      padding: [0, 5],
                      rotate: -90,
                      margin: [0, 5],
                      align: 'left',
                      overflow: 'hidden'

                    }
                  }
                }
              }
            },
            expandAndCollapse: true,
            animationDuration: 550,
            animationDurationUpdate: 750
          }
        ]
      });
      // this.myChart.on('click', this.turnDetails);
      this.myChart.on('click', this.chartResize);
      this.myChart.on('contextmenu', this.showMenu);
      this.chartResize()
    },
    chartResize() {
      var container = document.getElementById('tree-chart');
      var allNode = 0;
      var nodes = this.myChart._chartsViews[0]._data._graphicEls;
      for (var i = 0, count = nodes.length; i < count; i++) {
        var node = nodes[i];
        if (node === undefined)
          continue;
        allNode++;
      }
      var height = window.innerHeight - 200;
      var currentHeight = 80 * allNode;

      if(allNode<15){
        var currentHeight = 130 * allNode;
      }
      if(allNode<5){
        var currentHeight = 200 * allNode;
      }
      var newWidth = Math.max(currentHeight, height);
      container.style.width = window.innerWidth + 330 + 'px';
      container.style.height = newWidth + 'px';
      container.scrollTo(0, newWidth / 2 + 'px')

      this.myChart.resize();
    },
    showMenu(e) {
      this.searchId = e.data["AccountID"]
      this.menuFlag = true
      this.myChart.dispatchAction({
        //点击右键，隐藏tooltips
        type: 'hideTip',
      });
      var tree = document.getElementById('tree-chart');
      tree.oncontextmenu = function () {
        return false;
      };
      tree.getElementsByTagName("div")[0].style.position = "absolute"
      this.myMenuLeft = e.event.offsetX;
      this.myMenuTop = e.event.offsetY;
      this.getAttr(e.data)
    },
    async getAttr(data) {
      console.log(data)
      this.menuData = {
        "CompanyName": data.CompanyName,
        "CRMID": data.AccountID,
        "ContactAddress": 'static',
        "state": data.state
      };
      try {
        // let res = await api.getTreeDetails({"bp_account_id": data["AccountID"]})
        // if (res.status) {
        //   this.visitData = {
        //     "customer": res.data.data.CRMID,
        //     "customer_name": res.data.data.CompanyName,
        //     "type": res.data.data.type
        //   }
        //   this.menuData = res.data.data
        //   if(data.state == "1"){
        //     this.menuData["state"] = "Traded in the past year"
        //   }
        //   if(data.state == "2"){
        //     this.menuData["state"] = "Traded in the past three years "
        //   }
        //   if(data.state == "3"){
        //     this.menuData["state"] = "Didn't trade in the past three years"
        //   }
        // }
      } catch (e) {
        console.log(e);
      }
    },
    getNode(json, nodeId) {
      var parentNode = null
      //1.第一层 root 深度遍历整个JSON
      for (var i = 0; i < json.length; i++) {
        if (this.node) {
          break;
        }
        var obj = json[i];
        parentNode = obj;
        if (!obj || !obj["AccountID"]) {
          continue;
        }
        if (obj["AccountID"] == nodeId) {
          this.node = obj;
          break;
        } else {
          if (obj.children) {
            this.getNode(obj.children, nodeId);
          } else {
            continue;
          }
        }
      }
      if (this.node == null) {
        parentNode = null;
      }
      if (parentNode !== null) {
        console.log(parentNode)
        parentNode["collapsed"] = false;
        if(parentNode["AccountID"] == nodeId){
          parentNode["collapsed"] = true;
        }
      }
    },
    dataFun(obj) {
      let that = this
      var node = null
      obj["name"] = obj["CompanyName"]
      obj["label"] = this.treeBgColor(obj)
      obj["name"] = this.treeName(obj["name"])
      if (obj.children) {
        obj["name"] = "●● " + obj["name"]
        obj.children.forEach(function (key) {
          that.dataFun(key)
        })
      } else {
        return obj
      }
    },
    treeName(key) {
      if (key == undefined) return;

        if(key.match(/[\uff00-\uffff]/g) !== null && key.length > 15){
          key = key.substring(0, 14) + "..."
        }else{
            if (key.length > 27) {
              key = key.substring(0, 26) + "..."
            }
        }

      return key
    },
    treeBgColor(obj) {
      let style = {shadowBlur: 0, shadowColor: '#fff', shadowOffsetY: 0, shadowOffsetX: 0}
      if (obj["AccountID"] == this.searchValue) {
        style = {
          "overflow": 'hidden',
          "shadowColor": "#e4e7ed",
          // "backgroundColor":"#F8EAFF",
          "width": 250,
          "height": 30,
          "shadowBlur": 4,
          "shadowOffsetY": 5,
          "lineHeight": 35,
          "borderColor": "#82B4E8",
          "borderWidth": 2,
          rich: {
            box: {
              color: '#000',
              "fontWeight": 600,
            }
          }
        }
      }
      if (obj.state == "1") {
        this.state1 = true
        return {...style, backgroundColor: '#DAEAFF'}
      }
      if (obj.state == "2") {
        this.state2 = true
        return {...style, backgroundColor: '#F8EAFF'}
      }
      if (obj.state == "3") {
        this.state3 = true
        return {...style, backgroundColor: '#F2F2F2'}
      }
      if (obj.state == "4") {
        this.state4 = true
        return {...style, backgroundColor: '#F8EAFF'}
      }
      if (obj.state == null) {
        return style
      }
    },
  }
}
</script>
 
<style scoped lang="scss">
  .hierarchy-tree {
    padding: 10px;
    border-radius: 3px;
    position: relative;
    top: 20px;
    bottom: 60px;
    left: 0px;
    right: 10px;

    .table-top {
      position: fixed;
      top: 90px;
      z-index: 97;
    }
    br{
      margin-bottom: 3px;
    }
    #small-menu {
      min-width:100px;
      min-height:50px;
      padding: 20px 20px 30px 20px;
      background: #ffffff;
      color: #7E7E7E;
      position: relative;
      border-radius: 3px;
      border: 1px solid #A9CAFF;
      box-shadow: 0 0 3px #a9a9a9;
      z-index: 99999999;
      float: left;
      width: fit-content;
      span{
        display: inline-block;
        margin-bottom: 4px;
      }
    }

    .chart-flag {
      position: absolute;
      left: 50%;
      top: 100px;
    }

    .el-scrollbar__wrap {
      overflow-x: hidden;
    }

    .tree-chart-main {
      height: 75vh;

      #tree-chart {
        width: 100%;
        height: 75vh;
      }
    }

    .hierarchy-state {
      font-size: 12px;
      z-index: 9;
      width: 220px;
      position: fixed;
      top: 190px;
      left: 130px;
      text-align: right;
      .state {
        color: #6D6D6D;
        margin-bottom: 3px;
        cursor: pointer;

        span {
          width: 20px;
          height: 7px;
          display: inline-block;
          border-radius: 4px;
          margin-left: 5px;
        }
      }

      .state1 {
        span {
          background-color: #B8B8B8;
        }
      }

      .state2 {
        span {
          background-color: #FFA0E2;
        }
      }

      .state3 {
        span {
          background-color: #56A1FF;
        }
      }

      .state4 {
        span {
          background-color: #B665DB;
        }
      }
    }
  }
</style>